package qingxin.servlet.client.vote;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import qingxin.dao.VoteOptionDAO;
import qingxin.factory.DAOFactory;
import qingxin.vo.VoteOption;

@WebServlet("/client/vote/vote")
public class VotingServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private VoteOptionDAO voteOptionDAO;

	public VotingServlet(){
		super();
		voteOptionDAO = DAOFactory.getVoteOptionDAO();
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		try{
			int voteOptionID = Integer.parseInt(request.getParameter("oid"));

			voteOptionDAO.addNumber(voteOptionID);

			int voteID = voteOptionDAO.getByID(voteOptionID).getVoteID();
			
			VoteOption[] options = voteOptionDAO.getByVoteID(voteID);
			JSONObject jsonResult = new JSONObject();
			JSONArray jsonOptions = new JSONArray();
			int sum = 0;
			for(VoteOption option : options){
				JSONObject jsonOption = new JSONObject();
				jsonOption.put("id", option.getVoteOptionID());
				int number = option.getNumber();
				sum += number;
				jsonOption.put("number", number);
				jsonOptions.put(jsonOption);
			}
			jsonResult.put("options", jsonOptions);
			jsonResult.put("sum", sum);
	
			writer.println(jsonResult.toString());
			
			response.setStatus(HttpServletResponse.SC_OK);
		}
		catch(Exception e){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			writer.println("{\"msg\":\"wrong\"}");
		}
		finally{
			writer.flush();
			writer.close();
		}
	}
}

